package com.ryder.petmatediarybackend.module.social.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.petmatediarybackend.common.enums.ResultCode;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.pet.entity.PetProfile;
import com.ryder.petmatediarybackend.module.pet.entity.SysUser;
import com.ryder.petmatediarybackend.module.pet.service.PetProfileService;
import com.ryder.petmatediarybackend.module.pet.service.SysUserService;
import com.ryder.petmatediarybackend.module.social.dto.CreatePostDTO;
import com.ryder.petmatediarybackend.module.social.entity.SocialPost;
import com.ryder.petmatediarybackend.module.social.entity.SocialPostLike;
import com.ryder.petmatediarybackend.module.social.mapper.SocialPostMapper;
import com.ryder.petmatediarybackend.module.social.mapper.SocialPostLikeMapper;
import com.ryder.petmatediarybackend.module.social.service.SocialPostService;
import com.ryder.petmatediarybackend.module.social.vo.PostVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 社交动态表（仅支持图片，公开或私密）(SocialPost)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025-10-31 03:35:59
 */
@Slf4j
@Service("socialPostService")
@RequiredArgsConstructor
public class SocialPostServiceImpl extends ServiceImpl<SocialPostMapper, SocialPost> implements SocialPostService {

    private final SysUserService sysUserService;
    private final PetProfileService petProfileService;
    private final SocialPostLikeMapper socialPostLikeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PostVO createPost(Long userId, CreatePostDTO dto) {
        log.info("[社交动态] 用户ID={} 创建动态, 类型={}, 内容={}", userId, dto.getPostType(), dto.getContent());

        // 如果关联宠物ID，校验宠物是否属于当前用户
        if (dto.getPetId() != null) {
            PetProfile pet = petProfileService.getById(dto.getPetId());
            if (pet == null || !pet.getUserId().equals(userId)) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "宠物不存在或无权关联");
            }
        }

        // 创建动态实体
        SocialPost post = new SocialPost();
        post.setUserId(userId);
        post.setPetId(dto.getPetId());
        post.setPostType(dto.getPostType());
        post.setCircleId(dto.getCircleId());
        post.setContent(dto.getContent());
        post.setPrivacyLevel(dto.getPrivacyLevel());
        post.setLocation(dto.getLocation());
        
        // 将图片列表转为JSON字符串存储
        if (dto.getMediaUrls() != null && !dto.getMediaUrls().isEmpty()) {
            post.setMediaUrls(JSONUtil.toJsonStr(dto.getMediaUrls()));
        }
        
        // 初始化统计字段
        post.setLikeCount(0);
        post.setForwardCount(0);
        post.setViewCount(0);
        post.setIsTop(0);
        post.setIsRecommended(0);
        post.setAuditStatus(1); // 默认审核通过
        post.setStatus(1); // 正常状态

        // 保存到数据库
        this.save(post);
        log.info("[社交动态] 用户ID={} 创建动态成功, 动态ID={}", userId, post.getId());

        // 返回VO
        return convertToVO(post, userId);
    }

    @Override
    public List<PostVO> getPetCirclePosts(Long currentUserId) {
        log.info("[社交动态] 获取宠物圈子动态列表, 用户ID={}", currentUserId);

        // 查询条件：postType=1（宠物圈子）、privacyLevel=1（公开）、auditStatus=1（审核通过）、auditorId不为空（已审核）、status=1（正常）
        LambdaQueryWrapper<SocialPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SocialPost::getPostType, 1)
                .eq(SocialPost::getPrivacyLevel, 1)
                .eq(SocialPost::getAuditStatus, 1)
                .isNotNull(SocialPost::getAuditorId)  // auditor_id 不为空
                .eq(SocialPost::getStatus, 1)
                .orderByDesc(SocialPost::getIsTop)  // 置顶优先
                .orderByDesc(SocialPost::getCreateTime);  // 按创建时间倒序

        List<SocialPost> posts = this.list(queryWrapper);
        log.info("[社交动态] 获取宠物圈子动态列表成功, 数量={}", posts.size());

        // 转换为VO
        return posts.stream()
                .map(post -> convertToVO(post, currentUserId))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PostVO getPostDetail(Long userId, Long postId) {
        log.info("[社交动态] 用户ID={} 获取动态详情, 动态ID={}", userId, postId);

        SocialPost post = this.getById(postId);
        if (post == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "动态不存在");
        }

        // 增加浏览量
        post.setViewCount(post.getViewCount() + 1);
        this.updateById(post);

        return convertToVO(post, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePost(Long userId, Long postId) {
        log.info("[社交动态] 用户ID={} 删除动态, 动态ID={}", userId, postId);

        SocialPost post = this.getById(postId);
        if (post == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "动态不存在");
        }

        // 校验是否是本人的动态
        if (!post.getUserId().equals(userId)) {
            throw new BusinessException(ResultCode.FORBIDDEN, "无权删除他人动态");
        }

        // 逻辑删除
        this.removeById(postId);
        log.info("[社交动态] 用户ID={} 删除动态成功, 动态ID={}", userId, postId);
    }

    /**
     * 将Entity转换为VO
     */
    private PostVO convertToVO(SocialPost post, Long currentUserId) {
        PostVO vo = new PostVO();
        BeanUtils.copyProperties(post, vo);

        // ID转String
        vo.setId(post.getId().toString());
        vo.setUserId(post.getUserId().toString());
        if (post.getPetId() != null) {
            vo.setPetId(post.getPetId().toString());
        }
        if (post.getCircleId() != null) {
            vo.setCircleId(post.getCircleId().toString());
        }

        // 填充用户信息
        SysUser user = sysUserService.getById(post.getUserId());
        if (user != null) {
            vo.setUserName(user.getNickname());
            vo.setUserAvatar(user.getAvatar());
        }

        // 填充宠物信息
        if (post.getPetId() != null) {
            PetProfile pet = petProfileService.getById(post.getPetId());
            if (pet != null) {
                vo.setPetName(pet.getPetName());
                vo.setPetAvatar(pet.getAvatar());
            }
        }

        // 解析图片列表
        if (post.getMediaUrls() != null && !post.getMediaUrls().isEmpty()) {
            List<String> mediaList = JSONUtil.toList(post.getMediaUrls(), String.class);
            vo.setMediaUrls(mediaList);
        } else {
            vo.setMediaUrls(Collections.emptyList());
        }

        // 当前用户是否已点赞
        if (currentUserId != null) {
            LambdaQueryWrapper<SocialPostLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(SocialPostLike::getPostId, post.getId())
                    .eq(SocialPostLike::getUserId, currentUserId)
                    .eq(SocialPostLike::getIsDeleted, 0);
            long likeCount = socialPostLikeMapper.selectCount(likeWrapper);
            vo.setHasLiked(likeCount > 0);
        } else {
            vo.setHasLiked(false);
        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void likePost(Long userId, Long postId) {
        log.info("[社交动态] 用户ID={} 点赞动态, 动态ID={}", userId, postId);

        // 检查动态是否存在
        SocialPost post = this.getById(postId);
        if (post == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "动态不存在");
        }

        // 检查是否已点赞
        LambdaQueryWrapper<SocialPostLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SocialPostLike::getPostId, postId)
                .eq(SocialPostLike::getUserId, userId)
                .eq(SocialPostLike::getIsDeleted, 0);
        
        Long existingLike = socialPostLikeMapper.selectCount(queryWrapper);
        if (existingLike > 0) {
            log.warn("[社交动态] 用户ID={} 已点赞动态ID={}", userId, postId);
            return; // 已点赞，直接返回
        }

        // 创建点赞记录
        SocialPostLike like = new SocialPostLike();
        like.setPostId(postId);
        like.setUserId(userId);
        like.setIsDeleted(0);
        socialPostLikeMapper.insert(like);

        // 增加动态点赞数
        post.setLikeCount(post.getLikeCount() + 1);
        this.updateById(post);

        log.info("[社交动态] 用户ID={} 点赞动态成功, 动态ID={}", userId, postId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlikePost(Long userId, Long postId) {
        log.info("[社交动态] 用户ID={} 取消点赞动态, 动态ID={}", userId, postId);

        // 检查动态是否存在
        SocialPost post = this.getById(postId);
        if (post == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "动态不存在");
        }

        // 查找点赞记录
        LambdaQueryWrapper<SocialPostLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SocialPostLike::getPostId, postId)
                .eq(SocialPostLike::getUserId, userId)
                .eq(SocialPostLike::getIsDeleted, 0);
        
        SocialPostLike like = socialPostLikeMapper.selectOne(queryWrapper);
        if (like == null) {
            log.warn("[社交动态] 用户ID={} 未点赞动态ID={}", userId, postId);
            return; // 未点赞，直接返回
        }

        // 逻辑删除点赞记录
        like.setIsDeleted(1);
        socialPostLikeMapper.updateById(like);

        // 减少动态点赞数
        if (post.getLikeCount() > 0) {
            post.setLikeCount(post.getLikeCount() - 1);
            this.updateById(post);
        }

        log.info("[社交动态] 用户ID={} 取消点赞成功, 动态ID={}", userId, postId);
    }
}
